<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <div class="filter-group">
        <el-select
            v-model="data.selectedExam"
            placeholder="请选择考试"
            style="width: 150px; margin-left: 10px"
            clearable
        >
          <el-option
              v-for="exam in data.examOptions"
              :key="exam.examId"
              :label="exam.examName"
              :value="exam.examId"
          />
        </el-select>
      </div>
      <div class="filter-group">
        <el-select
            v-model="data.selectedClass"
            placeholder="请选择班级"
            style="width: 150px; margin-left: 10px"
            clearable
        >
          <el-option
              value="all"
              label="所有班级"
              :key="'all-option'"
          />
          <el-option
              v-for="cls in data.classOptions"
              :key="cls"
              :label="cls"
              :value="cls"
          />
        </el-select>
      </div>
      <div class="filter-group" >
        <el-input size="large" clearable @clear="load" style="width: 200px;margin-left: 5px" v-model="data.name"
                  placeholder="请输入学生姓名" prefix-icon="Search"></el-input>
      </div>

      <!-- 列显示控制开关 -->
      <div class="filter-group column-control">
        <el-checkbox-group v-model="data.columnVisible" @change="handleColumnChange">
          <el-checkbox label="className" border size="small">班级</el-checkbox>
          <el-checkbox label="studentNumber" border size="small">学号</el-checkbox>
          <el-checkbox label="seatNumber" border size="small">座号</el-checkbox>
        </el-checkbox-group>
      </div>

      <div class="filter-actions">
        <el-button type="primary" style="margin-left: 5px" @click="load">查 询</el-button>
        <el-button type="info" style="margin-left: 5px" @click="reset">重 置</el-button>
        <el-button v-if="data.user.role==='USER'" type="info" style="background-color: #7e55fc;margin-left: 5px"
                   @click="exportData">批量导出
        </el-button>

        <el-button
            type="success"
            style="margin-left: 5px"
            @click="setDefaultClass"
        >
          设为默认班级
        </el-button>
      </div>


      <!-- 提示信息 -->
      <el-tooltip
          v-if="data.defaultClass"
          :content="tooltipContent"
          placement="top"
      >
        <span class="default-class-indicator"><el-icon><Warning/></el-icon></span>
      </el-tooltip>
    </div>
    <div v-if="data.user.role==='ADMIN'" class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd" v-if="data.user.role==='ADMIN'">新 增</el-button>
      <el-button type="danger" @click="deleteBatch">批量删除</el-button>
      <el-upload style="display: inline-block;margin-left: 10px"
                 :action="`${BASE_URL}/scores/import`"
                 :show-file-list="false"
                 :before-upload="beforeExcelUpload"
                 :on-success="handleImportSuccess"
                 :data="{ examId: data.selectedExam }"
                 accept=".xls,.xlsx, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
        <el-button type="success" :loading="isUploading">批量导入</el-button>
      </el-upload>
      <el-button type="info" style="background-color: #7e55fc;margin-left: 10px" @click="exportData">批量导出
      </el-button>
      <el-button type="danger" style="margin-left: 10px" @click="clearExamData">清空该次考试数据
      </el-button>
    </div>

    <div class="card" style="margin-bottom: 5px; width: 100%;">
      <el-table stripe max-height="400"
                :data="data.tableData" style="width: 100%" @selection-change="handleSelectionChange"
                :header-cell-style="{color:'#333',backgroundColor:'#eaf4ff'}"
      >
        <el-table-column type="selection" width="55"/>

        <!-- 班级列 - 可控制显示/隐藏 -->
        <el-table-column
            v-if="data.columnVisible.includes('className')"
            prop="className"
            fixed
            label="班级"
        />

        <el-table-column prop="name" fixed  label="姓名"/>

        <!-- 学号列 - 可控制显示/隐藏 -->
        <el-table-column
            v-if="data.columnVisible.includes('studentNumber')"
            prop="studentNumber"
            sortable
            label="学号"
        />

        <!-- 座号列 - 可控制显示/隐藏 -->
        <el-table-column
            v-if="data.columnVisible.includes('seatNumber')"
            prop="seatNumber"
            sortable
            label="座号"
        />

        <el-table-column prop="score" sortable :formatter="formatScore" label="成绩"/>
        <el-table-column prop="classRank" sortable :formatter="formatScore" label="班排名"/>
        <el-table-column prop="gradeRank" sortable :formatter="formatScore" label="级排名"/>
        <el-table-column label="操作" width="150px">
          <template #default="scope">
            <el-button type="warning" icon="TrendCharts" circle @click="scoreAnalysis(scope.row)"></el-button>
            <el-button v-if="data.user.role==='ADMIN'" type="primary" icon="edit" circle
                       @click="handleEdit(scope.row)"></el-button>
            <el-button v-if="data.user.role==='ADMIN'" type="danger" icon="delete" circle
                       @click="del(scope.row.scoreId)"></el-button>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total,sizes, prev, pager, next,jumper"
          :page-sizes="[5, 20, 30, 40, 50, 100, 2000]"
          :total="data.total"
          @size-change="load"
          @current-change="load"/>
    </div>

    <el-dialog v-model="data.adminFormVisible" title="学生成绩信息" width="500px" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px" style="padding: 20px 30px 20px 0"
      >
        <el-form-item label="姓名" v-if="data.form.scoreId">
          <el-input v-model="data.form.name" placeholder="请输入学生名称" disabled autocomplete="off"/>
        </el-form-item>
        <el-form-item prop="studentName" label="姓名" v-else>
          <el-input v-model="data.form.studentName" placeholder="请输入学生名称" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="考试" v-if="data.form.scoreId">
          <el-input v-model="matchedExamName" placeholder="请选择考试" disabled autocomplete="off"/>
        </el-form-item>
        <el-form-item prop="examName" label="考试" v-else>
          <el-select
              v-model="data.form.examName"
              placeholder="请选择考试"
              clearable
          >
            <el-option
                v-for="exam in data.examOptions"
                :key="exam.examId"
                :label="exam.examName"
                :value="exam.examName"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="score" label="成绩">
          <el-input
              v-model="data.form.score"
              type="number"
              autocomplete="off"
              placeholder="请输入成绩"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.adminFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 成绩趋势分析Dialog -->
    <el-dialog
        style="margin-top: 30px"
        v-model="data.analysisDialogVisible"
        title="学生成绩趋势分析"
        width="800px"
        destroy-on-close
    >
      <div style="height: 500px;" id="trendChart"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.analysisDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import request from "@/utils/request";
import * as echarts from "echarts";
import {computed, onMounted, reactive, ref, watch} from "vue";
import {ElLoading, ElMessage, ElMessageBox, ElNotification} from "element-plus";
import { Warning } from '@element-plus/icons-vue'


const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || "{}"),
  name: null,
  selectedClass: localStorage.getItem('defaultClass') || '718',
  selectedExam: null,
  defaultClass: '',
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  adminFormVisible: false,
  form: {},
  rules: {
    studentName: [
      {required: true, message: '请输入学生名称', trigger: 'blur'}
    ],
    examName: [
      {required: true, message: '请选择考试名称', trigger: 'blur'}
    ],
    score: [
      {required: true, message: '请输入成绩', trigger: 'blur'}
    ]
  },
  rows: [],
  classOptions: [],
  examOptions: [],
  analysisDialogVisible: false,
  currentStudent: null,
  // 列显示控制相关
  columnVisible: ['className', 'studentNumber', 'seatNumber'], // 控制列显示的开关状态
  showClassName: true,
  showStudentNumber: true,
  showSeatNumber: true
})

// 提示信息计算属性
const tooltipContent = computed(() => {
  return `当前默认班级: ${data.defaultClass}`;
});

// 列显示状态变化处理
const handleColumnChange = (values) => {
  data.showClassName = values.includes('className');
  data.showStudentNumber = values.includes('studentNumber');
  data.showSeatNumber = values.includes('seatNumber');
}

onMounted(async () => {
  await fetchExams();
  fetchClasses()
  load()
});

const load = () => {
  request.get('/scores/page', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name?.trim(),
      selectedExam: data.selectedExam,
      selectedClass: data.selectedClass,
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data.records
      data.total = res.data.total
    } else {
      ElMessage.error(res.msg || '加载学生列表失败');
    }
  })
}

const fetchClasses = () => {
  request.get('/students/getClasses').then(res => {
    if (res.code === '200') {
      data.classOptions = res.data;
      data.classOptions.sort((a, b) => Number(a) - Number(b));
    } else {
      ElMessage.error(res.msg || '加载班级列表失败');
    }
  })
}

const fetchExams = () => {
  return request.get('/exams/getExams').then(res => {
    if (res.code === '200') {
      data.examOptions = res.data
          .slice()
          .sort((a, b) => new Date(b.examTime) - new Date(a.examTime));

      if (data.examOptions.length > 0) {
        data.selectedExam = data.examOptions[0].examId;
      }
    } else {
      ElMessage.error(res.msg || '加载考试列表失败');
    }
  })
}

const setDefaultClass = () => {
  data.defaultClass = data.selectedClass;
  localStorage.setItem('defaultClass', data.selectedClass);
  ElMessage.success(`已将 ${data.selectedClass} 设置为默认班级`);
}

const formRef = ref()

const reset = () => {
  data.name = null
  data.selectedClass = localStorage.getItem('defaultClass') || ''
  if (data.examOptions.length > 0) {
    data.selectedExam = data.examOptions[0].examId;
  }
  // 重置列显示状态为全部显示
  data.columnVisible = ['className', 'studentNumber', 'seatNumber'];
  handleColumnChange(data.columnVisible);
  load()
}

// 添加功能
const handleAdd = () => {
  data.adminFormVisible = true
  data.form = {}
}

const add = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.post('/scores/add', data.form).then(res => {
        if (res.code === '200') {
          data.adminFormVisible = false
          ElMessage.success('新增成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.adminFormVisible = true
}

const update = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.put('/scores/update', data.form).then(res => {
        if (res.code === '200') {
          data.adminFormVisible = false
          ElMessage.success('修改成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const save = () => {
  data.form.scoreId ? update() : add()
}

const del = (id) => {
  ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/scores/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
    ElMessage.info('已取消删除');
  })
}

const handleSelectionChange = (rows) => {
  data.rows = rows
}

const deleteBatch = () => {
  if (data.rows.length === 0) {
    ElMessage.warning('请选择数据')
    return
  }
  const ids = data.rows.map(row => row.scoreId)
  ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.post('/scores/deleteBatch', ids).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
  })
}
const BASE_URL = import.meta.env.VITE_API_BASE_URL;
const exportData = () => {
  if (data.rows.length > 0) {
    const ids = data.rows.map(item => item.studentId).join(',');
    const url = `${BASE_URL}/scores/export?examId=${data.selectedExam}&ids=${ids}`;
    window.open(url);
  } else {
    const params = new URLSearchParams();
    if (data.name) params.append('name', data.name);
    if (data.selectedExam) params.append('examId', data.selectedExam);
    if (data.selectedClass) params.append('selectedClass', data.selectedClass);

    const url = `${BASE_URL}/scores/export?${params.toString()}`;
    window.open(url);
  }
}

// 导入文件方法
const isUploading = ref(false);
let loadingInstance = null;
const closeLoading = () => {
  if (loadingInstance) {
    loadingInstance.close();
    loadingInstance = null;
  }
};

const beforeExcelUpload = (rawFile) => {
  if (!data.selectedExam) {
    ElMessage.error("请先选择考试！");
    return false;
  }
  loadingInstance = ElLoading.service({
    lock: true,
    text: '正在导入数据，请稍候...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  const isExcel =
      ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].includes(rawFile.type) ||
      ['.xls', '.xlsx'].some(ext => rawFile.name.toLowerCase().endsWith(ext));

  if (!isExcel) {
    ElMessage.error('仅支持上传 .xls 或 .xlsx 格式的 Excel 文件!');
    closeLoading();
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('文件大小不能超过10MB!')
    closeLoading();
    return false
  }
  isUploading.value = true;
  return true
}

const handleImportSuccess = (res) => {
  isUploading.value = false;
  closeLoading();
  if (res.code === '200') {
    ElMessage.success(res.data || '批量导入成功')
  } else {
    ElMessage.error(res.msg)
  }
  load()
}

const clearExamData = () => {
  ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/scores/clearExamData', {
      params: {selectedExam: data.selectedExam}
    }).then(res => {
      if (res.code === '200') {
        ElMessage.success('清除成功')
        fetchExams()
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
  })
}

// 计算属性：匹配考试名称
const matchedExamName = computed(() => {
  if (!data.examOptions.length || !data.form.examId) {
    return '';
  }

  const matchedExam = data.examOptions.find(
      exam => exam.examId === data.form.examId
  );

  return matchedExam ? matchedExam.examName : '';
});

// 图表相关
let trendChart = null;
const scoreAnalysis = (row) => {
  data.currentStudent = row;
  data.analysisDialogVisible = true;
  setTimeout(() => {
    loadScoreTrend(row.studentId);
  }, 100);
};

watch(() => data.analysisDialogVisible, (newVal) => {
  if (!newVal && trendChart) {
    trendChart.dispose();
    trendChart = null;
  }
});

const loadScoreTrend = (studentId) => {
  request.get(`/scores/trend/${studentId}`).then(res => {
    if (res.code === '200' && res.data.length > 0) {
      initCharts(res.data);
    } else {
      ElMessage.warning('暂无该学生的成绩数据');
      if (trendChart) {
        trendChart.clear();
      }
    }
  }).catch(() => {
    ElMessage.error('加载成绩趋势失败');
  });
};

const initCharts = (trendData) => {
  const examNames = trendData.map(item => item.examName);
  const scores = trendData.map(item => item.score !== null ? item.score : '-');
  const classRanks = trendData.map(item => item.classRank !== null ? item.classRank : '-');
  const gradeRanks = trendData.map(item => item.gradeRank !== null ? item.gradeRank : '-');

  const chartDom = document.getElementById('trendChart');
  if (!chartDom) {
    setTimeout(() => initCharts(trendData), 100);
    return;
  }

  if (!trendChart) {
    trendChart = echarts.init(chartDom);
  } else {
    trendChart = echarts.init(chartDom);
  }

  const option = {
    title: {
      text: `${data.currentStudent.name}的成绩与排名趋势`,
      left: 'center',
      bottom: 450,
      subtext: '点击可单独查看某项数据',
      subtextStyle: {fontSize: 12, color: '#666'},
      textStyle: {fontSize: 16},
      itemGap: 10
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let content = `${params[0].name}<br/>`;
        params.forEach(item => {
          const value = item.value === '-' ? '缺考' : item.value;
          content += `${item.seriesName}：${value}<br/>`;
        });
        return content;
      }
    },
    legend: {
      data: ['成绩', '班排名', '级排名'],
      top: 60,
      left: 'center',
      itemGap: 20,
      textStyle: {fontSize: 12}
    },
    grid: {
      top: 100,
      bottom: 80,
      left: 60,
      right: 60
    },
    xAxis: {
      type: 'category',
      data: examNames,
      axisLabel: {rotate: 30}
    },
    yAxis: [
      {
        type: 'value',
        name: '成绩',
        min: 0,
        max: 100,
        axisLabel: {formatter: '{value}分'},
        show: true
      },
      {
        type: 'value',
        name: '排名',
        inverse: true,
        axisLabel: {formatter: '{value}名'},
        position: 'right',
        splitLine: {show: false},
        min: 1,
        max: null,
        scale: true
      }
    ],
    series: [
      {
        name: '成绩',
        type: 'line',
        data: scores,
        symbol: 'circle',
        lineStyle: {width: 2, color: '#409EFF'},
        itemStyle: {color: '#409EFF'},
        yAxisIndex: 0,
        emphasis: {focus: 'series'}
      },
      {
        name: '班排名',
        type: 'line',
        data: classRanks,
        rawData: classRanks.filter(v => v !== '-'),
        symbol: 'circle',
        lineStyle: {width: 2, color: '#67C23A'},
        itemStyle: {color: '#67C23A'},
        yAxisIndex: 1
      },
      {
        name: '级排名',
        type: 'line',
        data: gradeRanks,
        symbol: 'circle',
        lineStyle: {width: 2, color: '#F56C6C'},
        itemStyle: {color: '#F56C6C'},
        yAxisIndex: 1,
        rawData: gradeRanks.filter(v => v !== '-'),
      }
    ]
  };

  trendChart.setOption(option);
  trendChart.on('legendselectchanged', function (params) {
    const selectedSeries = Object.keys(params.selected).filter(key => params.selected[key]);
    const visibleRankSeries = selectedSeries.filter(key => ['班排名', '级排名'].includes(key));

    if (visibleRankSeries.length === 0) {
      trendChart.setOption({
        yAxis: [
          {},
          {show: false}
        ]
      });
      return;
    }

    let allVisibleRankData = [];
    visibleRankSeries.forEach(seriesName => {
      const series = trendChart.getOption().series.find(s => s.name === seriesName);
      if (series && series.rawData) {
        allVisibleRankData = allVisibleRankData.concat(series.rawData);
      }
    });

    const dataMin = Math.min(...allVisibleRankData);
    const dataMax = Math.max(...allVisibleRankData);
    const padding = (dataMax - dataMin) * 0.1 || 5;

    trendChart.setOption({
      yAxis: [
        {},
        {
          show: true,
          min: Math.max(1, Math.floor(dataMin - padding)),
          max: Math.ceil(dataMax + padding)
        }
      ]
    });
  });
};

// 格式化成绩显示
const formatScore = (row, column, cellValue) => {
  if (cellValue === null || cellValue === undefined || cellValue === '') {
    return '缺考';
  }
  if (typeof cellValue === 'number' || cellValue instanceof BigDecimal) {
    return cellValue.toString();
  }
  return cellValue;
};
</script>

<style scoped>
.filter-group {
  display: inline-flex;
  align-items: center;
  margin-right: 20px;
  margin-bottom: 10px;
}

.filter-actions {
  display: inline-flex;
  align-items: center;
}

/* 列显示控制开关样式 */
.column-control {
  margin-top: 10px;
  padding: 5px 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.el-checkbox {
  margin-right: 15px !important;
  margin-bottom: 5px !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-group {
    display: block;
    margin-bottom: 15px;
  }

  .el-select, .el-input {
    width: 100% !important;
    margin-left: 0 !important;
    margin-bottom: 10px;
  }

  .filter-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 10px;
  }

  .el-button {
    flex: 1;
    min-width: 100px;
  }
}
</style>
